package org.rcy.framework.rpc.registry.thrift;

import org.apache.thrift.TException;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.transport.TMemoryBuffer;
import org.apache.thrift.transport.TMemoryInputTransport;
import org.rcy.framework.rpc.service.ServerNode;

public class NodeSerializer {

	public static byte[] write(ServerNode node) {
		try {
			TMemoryBuffer buffer = new TMemoryBuffer(1024);
			TBinaryProtocol protocol = new TBinaryProtocol(buffer);
			protocol.writeString(node.getHost());

			protocol.writeI32(node.getPort());
			protocol.writeI32(node.getWeight());
			return buffer.getArray();
		} catch (TException e) {
			return new byte[0];
		}
	}

	public static ServerNode read(byte[] bytes) {
		try {
			TMemoryInputTransport readBuffer = new TMemoryInputTransport(bytes);
			TBinaryProtocol protocol = new TBinaryProtocol(readBuffer);
			String host = protocol.readString();
			int port = protocol.readI32();
			int weight = protocol.readI32();
			ServerNode node = new ServerNode(host+":"+port+":"+weight);
			node.setWeight(weight);
			return node;
		} catch (TException e) {
			return new ServerNode("localhost:8000");
		}
	}
}
